import { defineStore } from 'pinia';
import { login, register, getCurrentUser, logout } from '../api/auth';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    loading: false,
    error: null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    isAdmin: (state) => state.user && state.user.is_staff,
    userFullName: (state) => {
      if (!state.user) return '';
      return `${state.user.first_name} ${state.user.last_name}`.trim() || state.user.username;
    }
  },
  
  actions: {
    async loginUser(credentials) {
      this.loading = true;
      this.error = null;
      try {
        const data = await login(credentials);
        this.token = data.access;
        await this.fetchCurrentUser();
        return data;
      } catch (error) {
        this.error = error.detail || '登录失败，请检查用户名和密码';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async registerUser(userData) {
      this.loading = true;
      this.error = null;
      try {
        const data = await register(userData);
        return data;
      } catch (error) {
        this.error = error.detail || '注册失败，请检查输入信息';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async fetchCurrentUser() {
      if (!this.token) return;
      
      this.loading = true;
      try {
        const user = await getCurrentUser();
        this.user = user;
        return user;
      } catch (error) {
        this.error = '获取用户信息失败';
        this.logoutUser();
      } finally {
        this.loading = false;
      }
    },
    
    logoutUser() {
      logout();
      this.user = null;
      this.token = null;
      this.error = null;
    }
  }
});